<template>
    <div>
        <el-upload class="image-uploader" :action="uploadApi"
            :data="fdata"
            :file-list="fileList"
            :with-credentials="withCredentials"
            :on-remove="handleRemove"
            :before-upload="beforeAvatarUpload"
            :on-change="handleChange"
            :list-type="listType">
            <el-button size="small" type="primary">{{btnName}}</el-button>
            <div slot="tip" class="el-upload__tip"> {{strFormat}} （上传文件大小不能超过 {{fsize}}MB!）</div>
        </el-upload>
    </div>
</template>

<script>
    import { uploadApi } from 'utils';

    export default {
      name: 'uploadImage',
      props: {
        //上传文件要提交的数据  
        fdata:{
            type:Object,
            default:function(){
                return {
                    'type':''
                }
            }
        },
        //文件大小 2M  
        fsize: {
            type: Number,
            default: 2
        },
        //文件长度，-1 默认上传多张图片，非 -1 只能上传一张图片
        flength:{
            type:Number,
            default:-1
        },
        //按钮文字
        btnName:{
            type:String,
            default:'点击上传'
        },
        //文件格式 传空数组时可以上传任意图片
        fileFormat:{
            type:Array,
            default:function(){
                return ['image/jpeg','image/png'];
            }
        },
        //文件缩略图
        listType:{
            type:String,
            default:'picture' //text/picture/picture-card
        },
        //初始化文件数组
        files:{
            type:Array,
            default: function () {
                return [];
            }
        }
      },
      data() {
        return {
            uploadApi:'',
            withCredentials:true,
            fileList:[]
        }
      },
      computed:{
        strFormat(){
            if(this.fileFormat.length > 0){
                return '只能上传' + this.fileFormat.join(',') + '文件';
            }
            return '';
        }
      },
      mounted(){
        this.uploadApi = uploadApi();
        let _files =  JSON.stringify(this.files);
        this.fileList = JSON.parse(_files);
      },
      methods:{
        getFileList(){
            console.log(this.fileList);
            return this.fileList;
        },  
        handleRemove(file, fileList) {
            this.fileList = fileList;
        },
        beforeAvatarUpload(file) {
            console.log(file);
            const isLt2M = file.size / 1024 / 1024 < this.fsize;

            let flag = false;
            for(let i = 0,l=this.fileFormat.length;i<l;i++){
                if(file.type == this.fileFormat[i]){
                    flag = true;
                    break;
                }
            }
            if(!flag && this.fileFormat.length > 0){
                this.$message.error(`上传图片只能是 ${this.strFormat} 格式!`);
                return false;
            }
            if (!isLt2M) {
                this.$message.error(`上传图片大小不能超过 ${this.fsize}MB!`);
                return false;
            }
            return true;
        },
        handleChange(file, fileList) {
            if(file.response && file.response.code == 10){
                let _l = fileList.length-1;
                fileList.splice(_l, 1);
                this.$confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$store.dispatch('LogOut').then(() => {
                        location.reload();// 为了重新实例化vue-router对象 避免bug
                    });
                }).catch(() => {

                });
                return;
            }
            if(file.response && file.response.code !=1){
                file.response.msg && this.$message.error(file.response.msg);
                let _l = fileList.length-1;
                fileList.splice(_l, 1);
                this.fileList = fileList;
                return;
            }
            if(file.response && file.response.code == 1){
                file.response.msg && this.$message({
                    message: file.response.msg,
                    type: 'success'
                });
                if(this.flength != -1 && fileList.length > this.flength){
                    fileList.splice(0, 1);
                }
                this.fileList = fileList;
            }
        }
      }
    }
</script>

